<?php

/**
 * @version $Id$
 * @package
 * @author Alexander Anokhin <ava@vaz.ru>
 */
class SuggestController extends Zend_Controller_Action
{
	
	protected $_session;
	
	public function init()
	{
		$this->_helper->Layout->disableLayout(true);
		$this->_helper->ViewRenderer->setNoRender(true);
		//Zend_Controller_Action_HelperBroker::addPath('JQuery/Controller/Action/Helper','ZendX_JQuery_Controller_Action_Helper');
		//Zend_Controller_Action_HelperBroker::addHelper(new ZendX_JQuery_Controller_Action_Helper_AutoComplete);
		Zend_Db_Table::setDefaultAdapter($this->_helper->connManager->getConnection());
		$this->_session = Zend_Controller_Front::getInstance()->getParam('session');
	}

	public function districtsAction()
	{
		if($chosen = $this->_request->getParam('chosen')) {$this->_session->id_dist = $chosen;return;}
		
		$this->_fetchAndSendSuggestions(new Kladr_Districts, array(
												'filterFields' => array('id_iso','id_er')
												));
	}
	
	public function regionsAction()
	{
		if($chosen = $this->_request->getParam('chosen')) {$this->_session->id_er = $chosen;return;}
		
		$this->_fetchAndSendSuggestions(new Kladr_Regions, array(
												'filterFields' => array('id_iso')
												));
	}
	
	public function countriesAction()
	{
		if($id_iso = $this->_request->getParam('chosen')) {$this->_session->id_iso = $id_iso;return;}

		$this->_fetchAndSendSuggestions(new Kladr_Countries);
	}
	
	public function companiesAction()
	{
		$this->_fetchAndSendSuggestions(new Kladr_Companies, array(
												'filterFields' => array()
												));
	}
	
	public function citiesAction()
	{
		$this->_fetchAndSendSuggestions(new Kladr_Cities, array(
												'filterFields' => array('id_iso','id_er','id_dist')
												));
	}
	
	public function streetsAction()
	{
		
	}
	
	protected function _fetchAndSendSuggestions($model, $opts = array())
	{
		
		foreach((array)$opts['filterFields'] as $fieldName)
		{
			if($value = $this->_session->$fieldName)
			{
				$model->addFilter($fieldName, $value);
			}
		}
		
		foreach($model->suggest(Util::iconvLdapToApp($this->_request->getParam('q')),
													$this->_request->getParam('limit')) as $k => $v)
		{
			$output .= $k."|".$v."\n";
		}
		
		die($output);
	}
}
